package com.qzxl.conntext.producer;

import com.alibaba.fastjson.JSONObject;
import com.qzxl.conntext.utils.NoGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class AccessProducer {

    private static final Logger logger = LoggerFactory.getLogger(AccessProducer.class);

    public static Map<String,String> idMap = new ConcurrentHashMap<>(); // 存放消息id+deviceName

    /**
     * esn 设备esn号，目前后台生成，保证唯一性
     * type 设备类型
     * name deviceName 采用设备号，保证唯一性
     */
    public void register(String esn, String type, String name , String deviceTitle,KafkaTemplate<String,String>kafkaTemplate){
        logger.info("****************************准备注册"+System.currentTimeMillis());
        try{
            JSONObject request = new JSONObject();
            JSONObject registerJson = new JSONObject();
            String uuid = NoGenerator.getUUID();
            registerJson.put("id",uuid);
            registerJson.put("requestTime",String.valueOf(NoGenerator.getDate()));
            request.put("serialNumber",esn);
            request.put("status",2);
            request.put("modelName",type);
            request.put("deviceName",name);
            request.put("deviceTitle",deviceTitle);
            registerJson.put("request",request);
            logger.info("----------------------------------发送注册消息"+System.currentTimeMillis());
            kafkaTemplate.send("sys."+type+".subdevice.register.request",type,registerJson.toJSONString());
            idMap.put(uuid,name);
            logger.info("----------------------------------------注册发送的消息是="+registerJson.toJSONString());
            logger.info("----------------------------------------已经成功发送注册消息");
        }catch (Exception e){
            logger.error("----------------------------------------注册失败--------------------------------------------");
            logger.error("--------------------------------------------错误消息是"+e);
        }
    }

}
